// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.MaterialPurchaseOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.DbOrganizationMapper;
import com.fowo.api.mapper.MaterialPurchaseOrderMapper;
import com.fowo.api.mapper.PurchaseOrderProductMapper;
import com.fowo.api.mapper.PurchaserMapper;
import com.fowo.api.mapper.SupplierMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.db.organization.DbOrganizationItemVo;
import com.fowo.api.model.db.organization.DbOrganizationSearchParamPo;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderBatchPurchasesOrderReviewAction;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderExcelPo;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderImportPo;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderItemVo;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderPurchasesOrderReviewAction;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderPushInStorageAction;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderSearchParamPo;
import com.fowo.api.model.material.purchase.order.MaterialPurchaseOrderVo;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderAnStatusEnums;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderArrivalStatusEnums;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderFeePartTypeEnums;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderIncludingTaxEnums;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderInspectionTypeEnums;
import com.fowo.api.model.material.purchase.order.constant.MaterialPurchaseOrderProductTypeEnums;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductSearchParamPo;
import com.fowo.api.model.purchaser.PurchaserItemVo;
import com.fowo.api.model.purchaser.PurchaserSearchParamPo;
import com.fowo.api.model.supplier.SupplierItemVo;
import com.fowo.api.model.supplier.SupplierSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.MaterialPurchaseOrderService;
import com.fowo.api.service.PurchaseOrderProductService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysDepartmentMapper;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDepartmentSearchParamPo;
import com.fowo.api.sys.model.SysDepartmentVo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 原材料采购订单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，沈友谅
 */
@Slf4j
@DataObjectType(MaterialPurchaseOrder.class)
@DS("ds24")
public class MaterialPurchaseOrderBaseServiceImpl
  extends ServiceImpl<MaterialPurchaseOrderMapper, MaterialPurchaseOrder>
  implements MaterialPurchaseOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("supplierIdSupplierName", "s.`supplier_name`");
      put("widName", "w.`name`");
      put("optUidName", "su.`name`");
      put("purchaserName", "p.`name`");
      put("oversightUidName", "su2.`name`");
      put("applicationDepName", "sd.`name`");
      put("orgIdName", "do.`name`");
      put("settlementOrgName", "do2.`name`");
      put("purchasesOrgName", "do3.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected MaterialPurchaseOrderService self;

  @Resource
  protected PurchaseOrderProductService purchaseOrderProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected SupplierMapper supplierMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected PurchaserMapper purchaserMapper;

  @Resource
  protected SysDepartmentMapper sysDepartmentMapper;

  @Resource
  protected DbOrganizationMapper dbOrganizationMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected MaterialPurchaseOrderBatchPurchasesOrderReviewAction materialPurchaseOrderBatchPurchasesOrderReviewAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected MaterialPurchaseOrderPurchasesOrderReviewAction materialPurchaseOrderPurchasesOrderReviewAction;

  @Autowired(required = false)
  protected MaterialPurchaseOrderPushInStorageAction materialPurchaseOrderPushInStorageAction;

  @Resource
  protected Validator validator;

  /**
   * 创建原材料采购订单
   * @param model 原材料采购订单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(MaterialPurchaseOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MaterialPurchaseOrder entity = new MaterialPurchaseOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getFeePartType() == null) {
      entity.setFeePartType("0");
    }

    if (model.getProductType() == null) {
      entity.setProductType("0");
    }

    if (model.getInspectionType() == null) {
      entity.setInspectionType("0");
    }

    if (model.getAnStatus() == null) {
      entity.setAnStatus("0");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getPurchaseOrderCode())) {
      entity.setPurchaseOrderCode(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "MaterialPurchaseOrder.purchaseOrderCode")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("原材料采购订单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 原材料采购订单
   */
  protected void updateAllChilds(MaterialPurchaseOrderVo model)
    throws Exception {
    if (model.getPurchaseOrde() != null) {
      purchaseOrderProductService.saveAllByPurchaseOrderId(
        model.getId(),
        model.getPurchaseOrde()
      );
    }
  }

  /**
   * 更新原材料采购订单
   * @param model 原材料采购订单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(MaterialPurchaseOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MaterialPurchaseOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("原材料采购订单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "productType",
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新原材料采购订单（带空值）
   * @param model 原材料采购订单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(MaterialPurchaseOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MaterialPurchaseOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("原材料采购订单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(MaterialPurchaseOrder::getSupplierId, model.getSupplierId())
      .set(MaterialPurchaseOrder::getWid, model.getWid())
      .set(MaterialPurchaseOrder::getContactPerson, model.getContactPerson())
      .set(MaterialPurchaseOrder::getContactNumber, model.getContactNumber())
      .set(
        MaterialPurchaseOrder::getSettlementMethod,
        model.getSettlementMethod()
      )
      .set(MaterialPurchaseOrder::getAdvanceRatio, model.getAdvanceRatio())
      .set(
        MaterialPurchaseOrder::getSettlementDescribe,
        model.getSettlementDescribe()
      )
      .set(MaterialPurchaseOrder::getPaymentMethod, model.getPaymentMethod())
      .set(
        MaterialPurchaseOrder::getPurchaseCurrency,
        model.getPurchaseCurrency()
      )
      .set(MaterialPurchaseOrder::getShippingPrice, model.getShippingPrice())
      .set(MaterialPurchaseOrder::getOtherCurrency, model.getOtherCurrency())
      .set(MaterialPurchaseOrder::getFeePartType, model.getFeePartType())
      .set(MaterialPurchaseOrder::getIncludingTax, model.getIncludingTax())
      .set(MaterialPurchaseOrder::getOptUid, model.getOptUid())
      .set(MaterialPurchaseOrder::getPurchaser, model.getPurchaser())
      .set(
        model.getOversightUid() != null,
        MaterialPurchaseOrder::getOversightUid,
        JSON.toJSONString(model.getOversightUid())
      )
      .setSql(model.getOversightUid() == null, "oversight_uid = null")
      .set(MaterialPurchaseOrder::getInspectionType, model.getInspectionType())
      .set(MaterialPurchaseOrder::getPurchasesDate, model.getPurchasesDate())
      .set(MaterialPurchaseOrder::getRemarks, model.getRemarks())
      .set(MaterialPurchaseOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(MaterialPurchaseOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(MaterialPurchaseOrder::getSettlementOrg, model.getSettlementOrg())
      .set(MaterialPurchaseOrder::getPurchasesOrg, model.getPurchasesOrg())
      .eq(MaterialPurchaseOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 采购详情(purchaseOrde) 对应的对象
    PurchaseOrderProductSearchParamPo purchaseOrdeSearchParam =
      new PurchaseOrderProductSearchParamPo();
    purchaseOrdeSearchParam.setDisableDataPremissions(true);
    purchaseOrdeSearchParam.setPurchaseOrderIdInList(ids);
    PurchaseOrderProductMapper localPurchaseOrderProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(PurchaseOrderProductMapper.class);
    purchaseOrdeSearchParam.applySqlSegments();
    List<Long> purchaseOrdeIdList = localPurchaseOrderProductMapper.searchIds(
      purchaseOrdeSearchParam
    );
    if (!purchaseOrdeIdList.isEmpty()) {
      PurchaseOrderProductService localPurchaseOrderProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(PurchaseOrderProductService.class);
      localPurchaseOrderProductService.batchDelete(purchaseOrdeIdList);
    }
  }

  /**
   * 删除原材料采购订单
   * @param id 原材料采购订单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除原材料采购订单
   * @param ids 原材料采购订单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<MaterialPurchaseOrderImportPo> excelToImportRow(
    MaterialPurchaseOrderImportPo row,
    Integer rowNumber,
    MaterialPurchaseOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<MaterialPurchaseOrderImportPo> ir =
      new ImportRow<MaterialPurchaseOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<MaterialPurchaseOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new MaterialPurchaseOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, MaterialPurchaseOrderImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getSettlementMethod())) {
      List<SysDictAllItem> settlementMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "settlementMethod",
          n -> sysDictService.getDictItems("SCM00004")
        );
      MaterialPurchaseOrderVo finalVo = vo;
      settlementMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSettlementMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSettlementMethod(i.getItemValue()),
          () ->
            ir.addError(
              "settlementMethod",
              String.format(
                "必须为 %s 中之一",
                settlementMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setAdvanceRatio(SheetUtils.tryToDecimal(row.getAdvanceRatio()));
    if (StringUtils.hasText(row.getPaymentMethod())) {
      List<SysDictAllItem> paymentMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "paymentMethod",
          n -> sysDictService.getDictItems("SCM00005")
        );
      MaterialPurchaseOrderVo finalVo = vo;
      paymentMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPaymentMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPaymentMethod(i.getItemValue()),
          () ->
            ir.addError(
              "paymentMethod",
              String.format(
                "必须为 %s 中之一",
                paymentMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPurchaseCurrency())) {
      List<SysDictAllItem> purchaseCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "purchaseCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      MaterialPurchaseOrderVo finalVo = vo;
      purchaseCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPurchaseCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPurchaseCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "purchaseCurrency",
              String.format(
                "必须为 %s 中之一",
                purchaseCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setShippingPrice(SheetUtils.tryToDecimal(row.getShippingPrice()));
    vo.setOtherCurrency(SheetUtils.tryToDecimal(row.getOtherCurrency()));
    if (StringUtils.hasText(row.getFeePartType())) {
      vo.setFeePartType(
        MaterialPurchaseOrderFeePartTypeEnums.toValue(row.getFeePartType())
      );
      if (vo.getFeePartType() == null) {
        ir.addError(
          "feePartType",
          "费用分摊方式只能是：“不分摊”, “按金额”, “按数量”"
        );
      }
    }
    if (StringUtils.hasText(row.getIncludingTax())) {
      vo.setIncludingTax(
        MaterialPurchaseOrderIncludingTaxEnums.toValue(row.getIncludingTax())
      );
      if (vo.getIncludingTax() == null) {
        ir.addError("includingTax", "含税只能是：“否”, “是”");
      }
    }
    if (StringUtils.hasText(row.getProductType())) {
      vo.setProductType(
        MaterialPurchaseOrderProductTypeEnums.toValue(row.getProductType())
      );
      if (vo.getProductType() == null) {
        ir.addError("productType", "产品类型只能是：“原材料”, “成品”");
      }
    }
    if (StringUtils.hasText(row.getInspectionType())) {
      vo.setInspectionType(
        MaterialPurchaseOrderInspectionTypeEnums.toValue(
          row.getInspectionType()
        )
      );
      if (vo.getInspectionType() == null) {
        ir.addError(
          "inspectionType",
          "质检类型只能是：“仓库质检”, “预检”, “免检”"
        );
      }
    }
    vo.setPurchasesDate(SheetUtils.tryToDate(row.getPurchasesDate()));
    SheetUtils.datePreviewFormat(row.getPurchasesDate(), row::setPurchasesDate);
    vo.setQuantityReceived(SheetUtils.tryToLong(row.getQuantityReceived()));
    if (StringUtils.hasText(row.getStauts())) {
      List<SysDictAllItem> stautsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "stauts",
          n -> sysDictService.getDictItems("SCM00020")
        );
      MaterialPurchaseOrderVo finalVo = vo;
      stautsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStauts()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStauts(i.getItemValue()),
          () ->
            ir.addError(
              "stauts",
              String.format(
                "必须为 %s 中之一",
                stautsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getArrivalStatus())) {
      vo.setArrivalStatus(
        MaterialPurchaseOrderArrivalStatusEnums.toValue(row.getArrivalStatus())
      );
      if (vo.getArrivalStatus() == null) {
        ir.addError(
          "arrivalStatus",
          "到货状态只能是：“未到货”, “部分到货”, “全部到货”"
        );
      }
    }
    vo.setCrossChecking(SheetUtils.tryToLong(row.getCrossChecking()));
    if (StringUtils.hasText(row.getAnStatus())) {
      vo.setAnStatus(
        MaterialPurchaseOrderAnStatusEnums.toValue(row.getAnStatus())
      );
      if (vo.getAnStatus() == null) {
        ir.addError(
          "anStatus",
          "审批状态只能是：“作废”, “待提交”, “待下单”, “待到货”, “已完成”, “待审批(审批流)”, “驳回(审批流)”, “作废(审批流)”"
        );
      }
    }
    vo.setOrderTime(SheetUtils.tryToDateTime(row.getOrderTime()));
    // 处理关联字段“供应商”
    if (
      !SheetUtils.isBlank(row.getSupplierIdSupplierName()) &&
      SheetUtils.isBlank(row.getSupplierId())
    ) {
      SupplierSearchParamPo supplierIdSearchParam = new SupplierSearchParamPo();
      supplierIdSearchParam.setLimit(2); // 最大只返回二行记录
      supplierIdSearchParam.setSupplierNameEq(
        SheetUtils.trim(row.getSupplierIdSupplierName())
      );
      supplierIdSearchParam.applySqlSegments();
      List<SupplierItemVo> supplierIdMatches = supplierMapper.search(
        supplierIdSearchParam
      );
      if (supplierIdMatches.size() == 0) {
        ir.addError("supplierIdSupplierName", "未能在供应商中找到匹配的数据");
      } else if (supplierIdMatches.size() > 1) {
        ir.addError(
          "supplierIdSupplierName",
          "关联不唯一，在供应商中找到多个匹配的数据"
        );
      } else {
        vo.setSupplierId(supplierIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWidName()) && SheetUtils.isBlank(row.getWid())
    ) {
      WarehouseSearchParamPo widSearchParam = new WarehouseSearchParamPo();
      widSearchParam.setLimit(2); // 最大只返回二行记录
      widSearchParam.setNameEq(SheetUtils.trim(row.getWidName()));
      widSearchParam.applySqlSegments();
      List<WarehouseItemVo> widMatches = warehouseMapper.search(widSearchParam);
      if (widMatches.size() == 0) {
        ir.addError("widName", "未能在仓库即时库存中找到匹配的数据");
      } else if (widMatches.size() > 1) {
        ir.addError(
          "widName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWid(widMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购员”
    if (
      !SheetUtils.isBlank(row.getOptUidName()) &&
      SheetUtils.isBlank(row.getOptUid())
    ) {
      SysUserSearch optUidSearchParam = new SysUserSearch();
      optUidSearchParam.setLimit(2); // 最大只返回二行记录
      optUidSearchParam.setNameEq(SheetUtils.trim(row.getOptUidName()));
      optUidSearchParam.applySqlSegments();
      List<SysUserItemVo> optUidMatches = sysUserMapper.search(
        optUidSearchParam
      );
      if (optUidMatches.size() == 0) {
        ir.addError("optUidName", "未能在用户中找到匹配的数据");
      } else if (optUidMatches.size() > 1) {
        ir.addError("optUidName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setOptUid(optUidMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购方”
    if (
      !SheetUtils.isBlank(row.getPurchaserName()) &&
      SheetUtils.isBlank(row.getPurchaser())
    ) {
      PurchaserSearchParamPo purchaserSearchParam =
        new PurchaserSearchParamPo();
      purchaserSearchParam.setLimit(2); // 最大只返回二行记录
      purchaserSearchParam.setNameEq(SheetUtils.trim(row.getPurchaserName()));
      purchaserSearchParam.applySqlSegments();
      List<PurchaserItemVo> purchaserMatches = purchaserMapper.search(
        purchaserSearchParam
      );
      if (purchaserMatches.size() == 0) {
        ir.addError("purchaserName", "未能在采购方中找到匹配的数据");
      } else if (purchaserMatches.size() > 1) {
        ir.addError(
          "purchaserName",
          "关联不唯一，在采购方中找到多个匹配的数据"
        );
      } else {
        vo.setPurchaser(purchaserMatches.get(0).getId());
      }
    }
    // 处理关联字段“单据负责人”
    if (
      !SheetUtils.isBlank(row.getOversightUidName()) &&
      SheetUtils.isBlank(row.getOversightUid())
    ) {
      SysUserSearch oversightUidSearchParam = new SysUserSearch();
      oversightUidSearchParam.setLimit(2); // 最大只返回二行记录
      oversightUidSearchParam.setNameEq(
        SheetUtils.trim(row.getOversightUidName())
      );
      oversightUidSearchParam.applySqlSegments();
      List<SysUserItemVo> oversightUidMatches = sysUserMapper.search(
        oversightUidSearchParam
      );
      if (oversightUidMatches.size() == 0) {
        ir.addError("oversightUidName", "未能在用户中找到匹配的数据");
      } else if (oversightUidMatches.size() > 1) {
        ir.addError(
          "oversightUidName",
          "关联不唯一，在用户中找到多个匹配的数据"
        );
      } else {
        vo.setOversightUid(
          oversightUidMatches
            .stream()
            .map(SysUserItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“申请部门”
    if (
      !SheetUtils.isBlank(row.getApplicationDepName()) &&
      SheetUtils.isBlank(row.getApplicationDep())
    ) {
      SysDepartmentSearchParamPo applicationDepSearchParam =
        new SysDepartmentSearchParamPo();
      applicationDepSearchParam.setLimit(2); // 最大只返回二行记录
      applicationDepSearchParam.setNameEq(
        SheetUtils.trim(row.getApplicationDepName())
      );
      applicationDepSearchParam.applySqlSegments();
      List<SysDepartmentVo> applicationDepMatches = sysDepartmentMapper.search(
        applicationDepSearchParam
      );
      if (applicationDepMatches.size() == 0) {
        ir.addError("applicationDepName", "未能在部门中找到匹配的数据");
      } else if (applicationDepMatches.size() > 1) {
        ir.addError(
          "applicationDepName",
          "关联不唯一，在部门中找到多个匹配的数据"
        );
      } else {
        vo.setApplicationDep(applicationDepMatches.get(0).getId());
      }
    }
    // 处理关联字段“组织id”
    if (
      !SheetUtils.isBlank(row.getOrgIdName()) &&
      SheetUtils.isBlank(row.getOrgId())
    ) {
      DbOrganizationSearchParamPo orgIdSearchParam =
        new DbOrganizationSearchParamPo();
      orgIdSearchParam.setLimit(2); // 最大只返回二行记录
      orgIdSearchParam.setNameEq(SheetUtils.trim(row.getOrgIdName()));
      orgIdSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> orgIdMatches = dbOrganizationMapper.search(
        orgIdSearchParam
      );
      if (orgIdMatches.size() == 0) {
        ir.addError("orgIdName", "未能在组织中找到匹配的数据");
      } else if (orgIdMatches.size() > 1) {
        ir.addError("orgIdName", "关联不唯一，在组织中找到多个匹配的数据");
      } else {
        vo.setOrgId(orgIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“结算组织”
    if (
      !SheetUtils.isBlank(row.getSettlementOrgName()) &&
      SheetUtils.isBlank(row.getSettlementOrg())
    ) {
      DbOrganizationSearchParamPo settlementOrgSearchParam =
        new DbOrganizationSearchParamPo();
      settlementOrgSearchParam.setLimit(2); // 最大只返回二行记录
      settlementOrgSearchParam.setNameEq(
        SheetUtils.trim(row.getSettlementOrgName())
      );
      settlementOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> settlementOrgMatches =
        dbOrganizationMapper.search(settlementOrgSearchParam);
      if (settlementOrgMatches.size() == 0) {
        ir.addError("settlementOrgName", "未能在组织中找到匹配的数据");
      } else if (settlementOrgMatches.size() > 1) {
        ir.addError(
          "settlementOrgName",
          "关联不唯一，在组织中找到多个匹配的数据"
        );
      } else {
        vo.setSettlementOrg(settlementOrgMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购组织”
    if (
      !SheetUtils.isBlank(row.getPurchasesOrgName()) &&
      SheetUtils.isBlank(row.getPurchasesOrg())
    ) {
      DbOrganizationSearchParamPo purchasesOrgSearchParam =
        new DbOrganizationSearchParamPo();
      purchasesOrgSearchParam.setLimit(2); // 最大只返回二行记录
      purchasesOrgSearchParam.setNameEq(
        SheetUtils.trim(row.getPurchasesOrgName())
      );
      purchasesOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> purchasesOrgMatches =
        dbOrganizationMapper.search(purchasesOrgSearchParam);
      if (purchasesOrgMatches.size() == 0) {
        ir.addError("purchasesOrgName", "未能在组织中找到匹配的数据");
      } else if (purchasesOrgMatches.size() > 1) {
        ir.addError(
          "purchasesOrgName",
          "关联不唯一，在组织中找到多个匹配的数据"
        );
      } else {
        vo.setPurchasesOrg(purchasesOrgMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<MaterialPurchaseOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<MaterialPurchaseOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            MaterialPurchaseOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              MaterialPurchaseOrderImportPo row,
              AnalysisContext cxt
            ) {
              MaterialPurchaseOrderVo vo = new MaterialPurchaseOrderVo();
              ImportRow<MaterialPurchaseOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<MaterialPurchaseOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<MaterialPurchaseOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      MaterialPurchaseOrderVo vo = new MaterialPurchaseOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"采购单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "purchaseOrderCode".equals(m.getField())
          )
      ) {
        vo.setPurchaseOrderCode(
          sysSerialService.getNewSerial(
            new NewSerialRequest(
              null,
              "MaterialPurchaseOrder.purchaseOrderCode"
            )
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    MaterialPurchaseOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "supplierId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MaterialPurchaseOrderItemVo) r).getSupplierIdSupplierName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "wid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((MaterialPurchaseOrderItemVo) r).getWidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "settlementMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00004")
      );
      exportOptions.addFieldMappingOption(
        "paymentMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00005")
      );
      exportOptions.addFieldMappingOption(
        "purchaseCurrency",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "feePartType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            MaterialPurchaseOrderFeePartTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "includingTax",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            MaterialPurchaseOrderIncludingTaxEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "optUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((MaterialPurchaseOrderItemVo) r).getOptUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "purchaser",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((MaterialPurchaseOrderItemVo) r).getPurchaserName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            MaterialPurchaseOrderProductTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "oversightUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MaterialPurchaseOrderItemVo) r).getOversightUidName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "inspectionType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            MaterialPurchaseOrderInspectionTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "purchasesDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "anStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            MaterialPurchaseOrderAnStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "settlementOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MaterialPurchaseOrderItemVo) r).getSettlementOrgName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "purchasesOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MaterialPurchaseOrderItemVo) r).getPurchasesOrgName()
            )
          )
      );
      exportOptions.addStringFields(
        "purchaseOrderCode",
        "supplierIdSupplierName",
        "widName",
        "contactPerson",
        "contactNumber",
        "settlementMethod",
        "settlementDescribe",
        "paymentMethod",
        "purchaseCurrency",
        "feePartType",
        "includingTax",
        "optUidName",
        "purchaserName",
        "productType",
        "oversightUidName",
        "inspectionType",
        "remarks",
        "totalPrice",
        "purchaseQuantity",
        "anStatus",
        "settlementOrgName",
        "purchasesOrgName"
      );

      String fileName = String.format(
        "原材料采购订单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> settlementMethodItems = sysDictService.getDictItems(
      "SCM00004"
    );
    List<SysDictAllItem> paymentMethodItems = sysDictService.getDictItems(
      "SCM00005"
    );
    List<SysDictAllItem> purchaseCurrencyItems = sysDictService.getDictItems(
      "SCM00015"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<MaterialPurchaseOrderExcelPo> items =
      new ArrayList<MaterialPurchaseOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<MaterialPurchaseOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<MaterialPurchaseOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (MaterialPurchaseOrderItemVo item : list) {
        MaterialPurchaseOrderExcelPo excel = new MaterialPurchaseOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getSettlementMethod() != null) {
          settlementMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSettlementMethod()))
            .findFirst()
            .ifPresent(i -> excel.setSettlementMethod(i.getItemText()));
        }
        if (item.getPaymentMethod() != null) {
          paymentMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPaymentMethod()))
            .findFirst()
            .ifPresent(i -> excel.setPaymentMethod(i.getItemText()));
        }
        if (item.getPurchaseCurrency() != null) {
          purchaseCurrencyItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPurchaseCurrency()))
            .findFirst()
            .ifPresent(i -> excel.setPurchaseCurrency(i.getItemText()));
        }
        excel.setFeePartType(
          MaterialPurchaseOrderFeePartTypeEnums.toLabel(item.getFeePartType())
        );
        excel.setIncludingTax(
          MaterialPurchaseOrderIncludingTaxEnums.toLabel(item.getIncludingTax())
        );
        excel.setProductType(
          MaterialPurchaseOrderProductTypeEnums.toLabel(item.getProductType())
        );
        excel.setInspectionType(
          MaterialPurchaseOrderInspectionTypeEnums.toLabel(
            item.getInspectionType()
          )
        );
        excel.setAnStatus(
          MaterialPurchaseOrderAnStatusEnums.toLabel(item.getAnStatus())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "原材料采购订单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(MaterialPurchaseOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过采购单号查询原材料采购订单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByPurNumSear(String purNumSear) {
    return this.baseMapper.getIdByPurNumSear(purNumSear);
  }

  /**
   * 通过采购单号查询原材料采购订单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByPurNumSear(List<String> list) {
    return this.baseMapper.getIdsByPurNumSear(list);
  }

  /**
   * 通过原材料采购订单主键查询采购单号
   */
  @Override
  public String getPurNumSearById(Long id) {
    return this.baseMapper.getPurNumSearById(id);
  }

  /**
   * 通过原材料采购订单主键查询采购单号列表
   */
  @Override
  public List<String> getPurNumSearByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getPurNumSearByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("purNumSear"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 原材料采购订单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public MaterialPurchaseOrderVo getVoById(Long id) throws Exception {
    MaterialPurchaseOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    PurchaseOrderProductSearchParamPo purchaseOrdeSearchParamPo =
      new PurchaseOrderProductSearchParamPo();
    purchaseOrdeSearchParamPo.setPurchaseOrderId(id);
    purchaseOrdeSearchParamPo.getExtendData().put("queryMode", "sub");
    purchaseOrdeSearchParamPo
      .getExtendData()
      .put("queryParent", "MaterialPurchaseOrder");
    purchaseOrdeSearchParamPo.applySqlSegments();
    vo.setPurchaseOrde(
      purchaseOrderProductService.search(purchaseOrdeSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询原材料采购订单
   * @param search 查询条件
   * @return 原材料采购订单分页查询结果
   */
  @Override
  public Page<MaterialPurchaseOrderItemVo> pageSearch(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    Page<MaterialPurchaseOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(MaterialPurchaseOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 原材料采购订单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'MaterialPurchaseOrderOptions::' + #search.keyword"
  )
  public List<OptionItem<MaterialPurchaseOrderItemVo>> searchOptions(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询原材料采购订单
   * @param search 查询条件
   * @return 原材料采购订单列表查询结果
   */
  @Override
  public List<MaterialPurchaseOrderItemVo> search(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询原材料采购订单最后更新时间
   * @param search 查询条件
   * @return 原材料采购订单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(MaterialPurchaseOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 批量审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量审核操作"
  )
  @Override
  public void batchPurchasesOrderReview(List<Long> ids) throws Exception {
    if (materialPurchaseOrderBatchPurchasesOrderReviewAction == null) {
      throw new Exception("此操作当前不可用");
    }
    materialPurchaseOrderBatchPurchasesOrderReviewAction.run(ids);
  }

  /**
   * 作废
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了作废操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void cancellation(List<Long> ids) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/MaterialPurchaseOrder_cancellation.js",
      ids,
      null,
      this
    );
  }

  /**
   * 审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审核操作"
  )
  @Override
  public void purchasesOrderReview(Long id) throws Exception {
    if (materialPurchaseOrderPurchasesOrderReviewAction == null) {
      throw new Exception("此操作当前不可用");
    }
    materialPurchaseOrderPurchasesOrderReviewAction.run(id);
  }

  /**
   * 下推采购入库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推采购入库单操作"
  )
  @Override
  public void pushInStorage(Long id) throws Exception {
    if (materialPurchaseOrderPushInStorageAction == null) {
      throw new Exception("此操作当前不可用");
    }
    materialPurchaseOrderPushInStorageAction.run(id);
  }

  /**
   * 全部
   */
  @Override
  public List<MaterialPurchaseOrderItemVo> quanbu(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.quanbu(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<MaterialPurchaseOrderItemVo> quanbuPage(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    Page<MaterialPurchaseOrderItemVo> quanbuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return quanbuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return quanbuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    quanbuPage =
      this.baseMapper.quanbuPage(
          search.toPage(this.baseMapper.quanbuCount(search)),
          search
        );
    List<Long> recordIds = quanbuPage
      .getRecords()
      .stream()
      .map(MaterialPurchaseOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return quanbuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return quanbuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    quanbuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return quanbuPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date quanbuLastUpdateTime(MaterialPurchaseOrderSearchParamPo search) {
    return this.baseMapper.quanbuLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<MaterialPurchaseOrderItemVo> daitijiao(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.daitijiao(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<MaterialPurchaseOrderItemVo> daitijiaoPage(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    Page<MaterialPurchaseOrderItemVo> daitijiaoPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return daitijiaoPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return daitijiaoPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    daitijiaoPage =
      this.baseMapper.daitijiaoPage(
          search.toPage(this.baseMapper.daitijiaoCount(search)),
          search
        );
    List<Long> recordIds = daitijiaoPage
      .getRecords()
      .stream()
      .map(MaterialPurchaseOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return daitijiaoPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return daitijiaoPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    daitijiaoPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return daitijiaoPage;
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date daitijiaoLastUpdateTime(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    return this.baseMapper.daitijiaoLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<MaterialPurchaseOrderItemVo> yiwancheng(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.yiwancheng(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<MaterialPurchaseOrderItemVo> yiwanchengPage(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    Page<MaterialPurchaseOrderItemVo> yiwanchengPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return yiwanchengPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return yiwanchengPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    yiwanchengPage =
      this.baseMapper.yiwanchengPage(
          search.toPage(this.baseMapper.yiwanchengCount(search)),
          search
        );
    List<Long> recordIds = yiwanchengPage
      .getRecords()
      .stream()
      .map(MaterialPurchaseOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return yiwanchengPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return yiwanchengPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    yiwanchengPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return yiwanchengPage;
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date yiwanchengLastUpdateTime(
    MaterialPurchaseOrderSearchParamPo search
  ) {
    return this.baseMapper.yiwanchengLastUpdateTime(search);
  }
}
